import axios from 'axios'
import iView from 'iview'
import { ResError } from './error/ResError'
import sf from 'string-format'
import store from '@/store'
import router from '@/router/index'
import config from '../config/index'

const baseRequestUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

const axiosInstance = axios.create({
  baseURL: baseRequestUrl,
  timeout: 3000,
  withCredentials: true
})
axiosInstance.interceptors.request.use(function (config) {
  // iView.LoadingBar.start()
  if (sessionStorage.getItem('token')) {
    config.headers.token = sessionStorage.getItem('token')
  }
  return config
}, function (error) {
  // iView.LoadingBar.finish()
  return Promise.reject(error)
})
// axiosInstance.interceptors.response.use(res => {
//   // iView.LoadingBar.finish()

//   // return res.data
//   return res;
// }, error => {
//   // iView.LoadingBar.finish();
//   if (error.response&&error.response['status'] == '401') {
//     localStorage.clear()
//     store.commit('setAccess', [])
//     iView.Message.error({
//       content: "没有找到登录用户，请重新登陆!",
//       duration: 3,
//       closable: true,
//       onClose: () => {
//         router.push({
//           name: 'login'
//         })
//       }
//     });

//     throw error;
//   }
//  throw new ResError('请求服务器失败，请检查服务是否正常！')
//   // return error;
// })

export const baseUrl = baseRequestUrl

export const get = (url, params, pathVariable = null) => {
  if (params == null) {
    params = { axios_timestamp_current: new Date().getTime() }
  } else {
    params.axios_timestamp_current = new Date().getTime()
  }
  return axiosInstance.get(sf(url, pathVariable), { params: params })
}

export const post = (url, params, pathVariable = null) => {
  return axiosInstance.post(sf(url, pathVariable), params);
}

export const put = (url, params, pathVariable = null) => axiosInstance.put(sf(url, pathVariable), params)

export const patch = (url, params, pathVariable = null) => axiosInstance.patch(sf(url, pathVariable), params)

export const del = (url, params, pathVariable = null) => axiosInstance.delete(sf(url, pathVariable), { params: params })
const commonMethods = {
  methods: {
    post: function (url, data, pathVariable) {
      this.$store.commit('showLoading');
      var obj = sf(url, pathVariable);
      return axiosInstance({
        method: 'post',
        url: sf(url, pathVariable),
        // emulateJSON: true,
        data: data,
        timeout: 50000
      }).then(
        (response) => {
          this.$store.commit('hideLoading');
          console.log(response);
          return response.data;
        }
      ).catch((error) => {
        console.log(error);
        this.$store.commit('hideLoading');
        this.handlerError(error);
        return Promise.reject(error);

      })
    },
    get: function (url,pathVariable) {
      this.$store.commit('showLoading');
      return axiosInstance({
        method: 'get',
        url: sf(url, pathVariable),
        timeout: 50000,
      }).then(
        (response) => {
          this.$store.commit('hideLoading');
          return response.data;
        }
      ).catch((error) => {
        console.log(error);
        this.$store.commit('hideLoading');
        this.handlerError(error);
        return Promise.reject(error);

      })
    },
    checkIsSsuccess: function (res) {
      if (res && res.status && res.status == '00') {
        return true;
      } else {
        return false;
      }
    }, getBaseUrl: function () {
      return baseUrl;
    }, handlerError(error) {
      if (!error) {
        iView.Message.error({
          content: "请求服务器失败，请检查服务是否正常！",
          duration: 3,
          closable: true
        });
      } else if (error.response) {
        if (error.response['status'] == '401') {
       
          // localStorage.clear()
          // sessionStorage.clear();
          // store.commit('setAccess', [])
          iView.Message.error({
            content: "没有找到登录用户，请重新登陆!",
            duration: 3,
            closable: true,
            onClose: () => {
              // router.push({
              //   name: 'login'
              // })
              this.$store.dispatch('handleLogOut').then(()=>{
                router.push({
                  name: 'login'
                })

              });
            }
          });
        }else if(error.response['status'] == '110'){
          iView.Message.error({
            content: "没有权限，请通知管理员！",
            duration: 3,
            closable: true
          });
        }else{
          iView.Message.error({
            content: "请求服务器失败，请检查服务是否正常！",
            duration: 3,
            closable: true
          });
        }
      }else{
        iView.Message.error({
          content: error.message,
          duration: 3,
          closable: true
        });
      }
    }
  }
}
export default commonMethods;